package com.hspedu.qqserver.service;

import com.hspedu.qqcommon.Message;
import com.hspedu.qqcommon.MessageType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/3/17
 * @time 21:02
 */
@SuppressWarnings("all")
public class ServerConnectClientThread extends Thread {

    private Socket socket;
    private String userId;
    private volatile boolean loop = true;

    public ServerConnectClientThread() {
    }

    public ServerConnectClientThread(Socket socket, String userId) {
        this.socket = socket;
        this.userId = userId;
    }

    public ServerConnectClientThread(Socket socket) {
        this.socket = socket;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        while (loop) {
            System.out.println("服务器和客户端保持通讯，读取数据...");
            try {
                System.out.println("服务器和客户端" + userId + "保持通讯");
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message acceptMessage = (Message) ois.readObject();

                //在这里根据message的类型做不同的处理
                String messageType = acceptMessage.getMessageType();
                switch (messageType) {
                    //客户端请求在线用户列表
                    case MessageType.MESSAGE_GET_ONLINE_FRIEND: {
                        System.out.println(acceptMessage.getSender() + "要获取在线用户列表");
                        HashMap<String, ServerConnectClientThread> allServerThreads = ManageServerConnectClientThread.getAllServerThreads();
                        Message message = new Message();
                        message.setContent("");
                        System.out.println(allServerThreads.size());
                        for (String userId : allServerThreads.keySet()) {
                            if (message.getContent() != null) {
                                message.setContent(message.getContent() + userId + " ");
                            }
                        }
                        message.setMessageType(MessageType.MESSAGE_RETURN_ONLINE_FRIEND);
                        message.setGetter(message.getSender());
                        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                        oos.writeObject(message);
                        oos.flush();
                        break;
                    }
                    //客户端请求退出
                    case MessageType.MESSAGE_CLIENT_EXIT: {
                        System.out.println(acceptMessage.getSender() + "客户端请求断开连接");
                        loop = false;
                        //ManageServerConnectClientThread.getServerConnectClientThread(userId).getSocket().close();
                        //这就是当前线程的socket
                        socket.close();
                        ManageServerConnectClientThread.deleteServerConnectClientThread(userId);
                        break;
                    }
                    //客户端请求群发消息
                    case MessageType.MESSAGE_TO_ALL: {
                        String content = acceptMessage.getContent();
                        String srcUser = acceptMessage.getSender();
                        HashMap<String, ServerConnectClientThread> allServerThreads =
                                ManageServerConnectClientThread.getAllServerThreads();
                        if (allServerThreads.size() != 1) {
                            ServerConnectClientThread srcUserThread =
                                    ManageServerConnectClientThread.getServerConnectClientThread(srcUser);
                            for (ServerConnectClientThread thread : allServerThreads.values()) {
                                if (thread != srcUserThread) {
                                    Socket socket = thread.getSocket();
                                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                                    oos.writeObject(acceptMessage);
                                    oos.flush();
                                }
                            }
                        } else {
                            //当前除了自己外无一人在线
                            Message message = new Message();
                            message.setContent("当前除了你之外无人在线");
                            LocalDateTime now = LocalDateTime.now();
                            String pattern = "yyyy年MM月dd日 HH时mm分ss秒";
                            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
                            String sendTime = dateTimeFormatter.format(now);
                            message.setSendTime(sendTime);
                            message.setMessageType(MessageType.MESSAGE_COMM_MES);
                            message.setSender("服务器");
                            ServerConnectClientThread srcUserThread =
                                    ManageServerConnectClientThread.getServerConnectClientThread(srcUser);
                            Socket socket = srcUserThread.getSocket();
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            oos.writeObject(message);
                            oos.flush();
                        }
                        break;
                    }
                    //客户端发送的普通消息，请求与指定用户私聊
                    case MessageType.MESSAGE_COMM_MES: {
                        //获取目标用户
                        String targetUser = acceptMessage.getGetter();
                        //获取消息内容
                        String content = acceptMessage.getContent();
                        //获取发送对象
                        String srcUser = acceptMessage.getSender();
                        ServerConnectClientThread targetUserThread =
                                ManageServerConnectClientThread.getServerConnectClientThread(targetUser);
                        //判断当前用户是否在线，如果在线就有对应的线程
                        if (targetUserThread != null) {
                            Socket socket = targetUserThread.getSocket();
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            oos.writeObject(acceptMessage);
                            oos.flush();
                        } else {
                            Message message = new Message();
                            message.setContent("你输入的用户当前不在线，无法接收到消息，此消息已保存在服务器端，" +
                                    "等到目标用户上线后会自动发送");
                            SendOfflineMessageService.setOfflineMessage(acceptMessage.getGetter(),acceptMessage);
                            LocalDateTime now = LocalDateTime.now();
                            String pattern = "yyyy年MM月dd日 HH时mm分ss秒";
                            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
                            String sendTime = dateTimeFormatter.format(now);
                            message.setSendTime(sendTime);
                            message.setMessageType(MessageType.MESSAGE_COMM_MES);
                            message.setSender("服务器");
                            ServerConnectClientThread srcUserThread =
                                    ManageServerConnectClientThread.getServerConnectClientThread(srcUser);
                            Socket socket = srcUserThread.getSocket();
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            oos.writeObject(message);
                            oos.flush();
                        }
                        break;
                    }
                    //客户端发送文件
                    case MessageType.MESSAGE_BINARY_DATA:{
                        //获取文件要保存到哪个对象
                        String getter = acceptMessage.getGetter();
                        ServerConnectClientThread thread =
                                ManageServerConnectClientThread.getServerConnectClientThread(getter);
                        if (thread != null) {
                            Socket socket = thread.getSocket();
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            oos.writeObject(acceptMessage);
                            oos.flush();
                        }else{
                            //这里可以在优化一下离线发送文件
                            //说明当前用户不在线
                            Message message = new Message();
                            message.setContent("你输入的用户当前不在线，无法发送消息");
                            LocalDateTime now = LocalDateTime.now();
                            String pattern = "yyyy年MM月dd日 HH时mm分ss秒";
                            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
                            String sendTime = dateTimeFormatter.format(now);
                            message.setSendTime(sendTime);
                            message.setMessageType(MessageType.MESSAGE_COMM_MES);
                            message.setSender("服务器");
                            String srcUser = acceptMessage.getSender();
                            ServerConnectClientThread srcUserThread =
                                    ManageServerConnectClientThread.getServerConnectClientThread(srcUser);
                            Socket socket = srcUserThread.getSocket();
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            oos.writeObject(message);
                            oos.flush();
                        }
                        break;
                    }

                    default:
                        System.out.println("其它类型的客户端消息请求,暂且不做处理");
                        break;
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        System.out.println(userId + "服务器端线程退出");
    }
}
